#include <iostream>
#include <stdlib.h>
#include "Parser.h"
#include "Lexer.h"


Parser::Parser(Lexer Lexatron){
    lexer = Lexatron;
}

void Parser::Expr(){
    Term();
    while (myToken.tCode == PLUS)
    {
	   cout << myToken.lexeme << endl;
	   lex();
        Expr();
		
    }
}

void Parser::Term(){
    Factor();
    while (myToken.tCode == MULT)
    {
		cout << myToken.lexeme << endl;
		lex();
        Term();
    }
}

void Parser::Factor(){
    if (this->myToken.tCode == INT){
		cout << myToken.lexeme << endl;
		lex();
		return;
	}
    else if (this->myToken.tCode == LPAREN){
        Expr();
		lex();
        if (this->myToken.tCode == RPAREN)
           return;
        else
            error();
    }
	else if(myToken.tCode != END){
	error();
	}

}

void Parser::parse() {
	lex();
    Expr();
    lex();
    if(myToken.tCode == END){
        cout << "PRINT";
        return;
    }
    else{
        error();
    }
}

void Parser::lex(){
    myToken = lexer.nextToken();

    if(myToken.tCode == ERROR)
        error();
}

void Parser::error(){
    cout << "Syntax error!" << endl;
    return exit(1);
}
